package cn.zhangmh.easymvp;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;

import cn.zhangmh.easymvp.books.entity.BookBean;
import cn.zhangmh.easymvp.books.entity.Books;
import cn.zhangmh.easymvp.books.BookPresenter;
import cn.zhangmh.easymvp.books.BookView;
import cn.zhangmh.easymvp.books.ui.BookBeanFragment;
import cn.zhangmh.easymvp.books.ui.BookInfoFragment;
import cn.zhangmh.easymvp.books.ui.SearchFragment;

public class MainActivity extends AppCompatActivity implements SearchFragment.OnFragmentInteractionListener,BookBeanFragment.OnListFragmentInteractionListener,BookInfoFragment.OnFragmentInteractionListener {


    private SearchFragment searchFragment;

    private  BookBeanFragment bookBeanFragment;

    private BookPresenter mBookPresenter = new BookPresenter(this);

    public  ImageLoader imageLoader ;

    private BookInfoFragment bookInfoFragment;

    private  String keywords;

    private  static final  String SEARCH_BOX = "search_box";

    private  static final String  BOOK_LIST = "book_list";

    private  static  final  String BOOK_INFO = "book_info";

    private  static  final  String DEBUG = "调试信息-->";

    private long mExitTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (searchFragment == null){
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
         searchFragment = SearchFragment.newInstance();
        fragmentTransaction.add(R.id.base_container,searchFragment,SEARCH_BOX).commit();
            searchFragment.setOnFragmentInteractionListener(this);
        }
        mBookPresenter.onCreate();
        mBookPresenter.attachView(mBookView);
    }

    private BookView mBookView = new BookView(){
        @Override
        public void onSuccess(Books mBook) {
            if (mBook != null ){
                 showBooksList(mBook);
            }
        }

        @Override
        public void onError(String result) {
            Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
        }
    } ;

    /**
     *  监听返回键事件，如果在查询界面按两次返回就退出程序，其他界面保持原有的后退功能
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && searchFragment.isVisible()) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected  void  onDestroy(){
        super.onDestroy();
        mBookPresenter.onStop();
    }

    /**
     * 查询界面点击按钮之后的事件处理
     * @param keywords
     */
    @Override
    public void onFragmentInteraction(String keywords) {
        this.keywords = keywords;
        mBookPresenter.getSearchBooks(this.keywords,null,0,20);
    }

    /**
     * 判断是否已经存在fragment,存在并且没有被替换就是刷新数据，被替换就移除旧的实例化新的，否则就更新fragment
     * @param books
     */
    protected   void  showBooksList(Books books){

        if (null == bookBeanFragment ||
                bookBeanFragment.getView() ==null){
            FragmentTransaction fmt = getFragmentManager().beginTransaction();
            if (null != bookBeanFragment && bookBeanFragment.getView() == null)
                fmt.remove(bookBeanFragment);
            bookBeanFragment =  BookBeanFragment.newInstance(books);
            bookBeanFragment.setOnListFragmentInteractionListener(this);
            fmt.replace(R.id.base_container,bookBeanFragment,BOOK_LIST);
            fmt.addToBackStack(null);
            fmt.commit();
        }else {
            bookBeanFragment.updateBooks(books);
        }
    }

    /**
     * 选中的图书信息
     * @param item
     */
    @Override
    public void onListFragmentInteraction(BookBean item) {
        bookInfoFragment = BookInfoFragment.newInstance(item);
        FragmentTransaction fmt = getFragmentManager().beginTransaction();
        fmt.replace(R.id.base_container,bookInfoFragment,BOOK_INFO);
        fmt.addToBackStack(BOOK_LIST);
        fmt.commit();
    }

    /**
     * 刷新当前数据
     */
    @Override
    public void onRefreashPull(@NonNull int total) {
        Log.d(DEBUG, "onRefreashPull: ");
        mBookPresenter.getSearchBooks(this.keywords,null,0,total);
    }

    /**
     * 加载更多数据
     * @param total
     */
    @Override
    public void onLoadingMorePull(@NonNull int total) {
        Log.d(DEBUG, "onLoadingMorePull: ");
        mBookPresenter.getSearchBooks(this.keywords,null,0,total+20);
    }

    @Override
    public void onFragmentInteraction() {

    }
}